﻿using Cxuu.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;

namespace Cxuu.Web.Authorize
{
    /// <summary>
    /// 授权判断
    /// </summary>
    public class ActionPermissionFilter : ActionFilterAttribute//, IAsyncActionFilter
    {
        public string Permission { get; set; }
        public ActionPermissionFilter() { }
        public ActionPermissionFilter(string permission)
        {
            Permission = permission;
        }

        /// <summary>
        /// 执行Action前校验是否有权限访问
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            LoginUtil login = context.HttpContext.RequestServices.GetService<LoginUtil>();
            UserInfo userInfo = await login.UserInfoAsync();
 
            if (userInfo.Gid != 1 && !userInfo.SystemRole.Exists(x => x == Permission))
            {
                JsonResult result = new(new { status = 0, msg = "没有权限操作此功能" })
                {
                    ContentType = "application/json",
                };
                context.Result = result;
            }
            else
                await base.OnActionExecutionAsync(context, next);
        }
    }
}
